package com.york.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.york.subject.common.entity.PageResult;
import com.york.subject.common.enums.IsDeletedFlagEnum;
import com.york.subject.common.util.LoginUtil;
import com.york.subject.domain.convert.SubjectInfoConverter;
import com.york.subject.domain.entity.SubjectInfoBO;
import com.york.subject.domain.entity.SubjectOptionBO;
import com.york.subject.domain.handler.subject.SubjectTypeHandler;
import com.york.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.york.subject.domain.redis.RedisUtil;
import com.york.subject.domain.service.SubjectInfoDomainService;
import com.york.subject.domain.service.SubjectLikedDomainService;
import com.york.subject.infra.basic.entity.SubjectInfo;
import com.york.subject.infra.basic.entity.SubjectInfoEs;
import com.york.subject.infra.basic.entity.SubjectLabel;
import com.york.subject.infra.basic.entity.SubjectMapping;
import com.york.subject.infra.basic.service.SubjectEsService;
import com.york.subject.infra.basic.service.SubjectInfoService;
import com.york.subject.infra.basic.service.SubjectLabelService;
import com.york.subject.infra.basic.service.SubjectMappingService;
import com.york.subject.infra.entity.UserInfo;
import com.york.subject.infra.rpc.UserRpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 注解Transactional表示多表操作的一个回滚机制
 */
@SuppressWarnings({"all"})
@Slf4j
@Service("subjectInfoDomainService")
@Transactional(rollbackFor = Exception.class)
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    // 引入工厂，根据枚举常量对应返回不同的策略，即不同的service
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private UserRpc userRpc;

    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject_rank";

    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        // 设计到设计模式
        // 假设全部写在主流程里面，判断type时，单选的调用单选service，多选的调用多选service...
        // 这样判断起来太复杂了，所以用 工厂 + 策略 的开发形式
        // 一个工厂 包含了 4种类型（单选、多选、判断、简答），根据输入的type自动映射选择处理
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        // 在insert的xml中设置了<selectKey>，已经把这次插入之后的自增长的id赋值给了subjectInfo的id属性
        subjectInfoService.insert(subjectInfo);
        // 通过不同的题型，还要为各种题型
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        // 在这里插入不同题型的时候要插入subject_id，这就是上面<selectKey>的用处
        subjectInfoBO.setId(subjectInfo.getId());
        log.info("SubjectInfoDomainServiceImpl.add.subjectInfoBO:{}", subjectInfoBO);
        handler.add(subjectInfoBO);
        // 因为插入题目时，mapping表作为题目的分类以及标签之间的关联映射，所以还需要把这个关联映射信息添加
        // 注意是多对多关系
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        LinkedList<SubjectMapping> mappingList = new LinkedList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setLabelId(Long.valueOf(labelId));
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode()); // 设置is_deleted属性
                mappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(mappingList);
    }

    /**
     * 分页查询,
     * 所有的一切都是要为了装配PageResult<SubjectInfoBO>
     * 表示使用泛型，其属性
     * private List<T> result = Collections.emptyList();
     * 即result属性此时对应 -> List<SubjectInfoBO>
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        // 根据categoryId/labelId/difficult得到符合条件的结果
        // 这里是个坑后续调整
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBO);
        // 先查到有多少条记录，即total
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBO.getCategoryId()
                , subjectInfoBO.getLabelId());
        if (count == 0) {
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBO.getCategoryId(),
                subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> boList = SubjectInfoConverter.INSTANCE.convertListInfoToBO(subjectInfoList);
        pageResult.setRecords(boList);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 查询题目信息,因为题目种类有多种，这里用上面的工厂，根据type返回不同种类查询的信息
     * 加入点赞相关的数据查询
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        Integer subjectType = subjectInfo.getSubjectType();
        // 根据题目类型获取handler
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO optionBO = handler.query(subjectInfo.getId());
        SubjectInfoBO bo = SubjectInfoConverter.INSTANCE.convertOptionAndInfoToBO(optionBO, subjectInfo);
        // 获取labelName
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        bo.setLabelName(labelNameList);
        // 加入点赞的数据
        bo.setLiked(subjectLikedDomainService.isLiked(subjectInfoBO.getId().toString(), LoginUtil.getLoginId()));
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId().toString()));
        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        bo.setLastSubjectId(lastSubjectId);
    }

    /**
     * es全文检索
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        return subjectEsService.querySubjectList(subjectInfoEs);
    }

    /**
     * 贡献榜
     * 用zset实现，无需和数据库相关
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (log.isInfoEnabled()) {
            log.info("getContributeList.typedTuples:{}", JSON.toJSONString(typedTuples));
        }
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach((rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            // zset的score
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            // zset的value,通过rpc调用返回
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        }));
        return boList;
    }
}
